package com.demo.service.riot.Async;

import com.demo.entity.riot.MatchInfo;
import com.demo.entity.riot.Summoner;
import com.demo.exception.ApiException;
import com.demo.mapper.riot.MatchMapper;
import com.demo.service.riot.SummonerService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@Service
public class MatchDataAsyncService {

    private static final Logger logger = LoggerFactory.getLogger(MatchDataAsyncService.class);

    @Resource
    private final MatchMapper matchMapper;

    private final SummonerService summonerService;

    public MatchDataAsyncService(MatchMapper matchMapper, SummonerService summonerService) {
        this.matchMapper = matchMapper;
        this.summonerService = summonerService;
    }

    private void insertMatchData(MatchInfo matchInfo) throws IOException {
        matchMapper.insertMatchInfo(matchInfo);
    }

    private void insertPlayerMatch(String puuid, MatchInfo matchInfo) {
        matchMapper.insertPlayerMatch(puuid, matchInfo.getMatchId(), matchInfo.getGameCreation());
    }

    // 使用指定的线程池执行器
    @Async("dataExecutor")
    public void processMatchDataAsync(String puuid, List<MatchInfo> matchInfos) {
        long startTime = System.currentTimeMillis();
        logger.info("开始异步处理比赛数据, puuid: {}, 比赛数量: {}", puuid, matchInfos.size());

        try {
            // 批量处理比赛数据
            addMatchInfo(puuid, matchInfos);
        } catch (Exception e) {
            logger.error("处理比赛数据时发生错误", e);
            // 这里可以添加错误处理逻辑，如重试或记录到数据库
        }

        long duration = System.currentTimeMillis() - startTime;
        logger.info("比赛数据处理完成, puuid: {}, 耗时: {}ms", puuid, duration);
    }

    public void addMatchInfo(String puuid, List<MatchInfo> matchInfos) throws ApiException, IOException {
        for (MatchInfo matchInfo : matchInfos) {
            List<Summoner> summoners = summonerService.getSummonerByMatchInfo(matchInfo);
            String matchId = matchInfo.getMatchId();
            if(!matchMapper.hasMatchInfo(matchId)) {
                insertMatchData(matchInfo);
            }
            for(Summoner summoner : summoners) {
                if(!matchMapper.hasPlayerMatch(summoner.getPuuid(), matchId)) {
                    insertPlayerMatch(summoner.getPuuid(), matchInfo);
                }
            }
        }
    }
}
